package com.htu.courseService.user.controller;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.htu.courseService.auth.service.EmailService;
import com.htu.courseService.common.enums.RedisCachePrefix;
import com.htu.courseService.common.util.RedisCache;
import com.htu.courseService.common.vo.R;
import com.htu.courseService.user.service.UserService;
import com.htu.courseService.user.vo.UserDTO;
import com.htu.courseService.user.vo.UserPasswordDto;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController implements RedisCachePrefix {
    private final UserService userService;

    private final EmailService emailService;

    private final RedisCache redisCache;

    /**
     * 导入用户excel模板
     * @param multipartFile
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadExcel")
    public R<List<String>> uploadReceivingExcel(@RequestParam(value = "multipartFile", required = true)
                                  MultipartFile multipartFile) throws IOException {
        List<String> userInfo = userService.uploadExcel(multipartFile);
        return R.success(userInfo);
    }

    /**
     * 下载导入用户excel模板
     * @param response
     */
    @GetMapping("/getExcel")
    public void getExcel(HttpServletResponse response){
        try {
            ClassPathResource classPathResource = new ClassPathResource("exdelTemplate/excelUpload.xlsx");
            File file = classPathResource.getFile();
            InputStream inputStream = classPathResource.getInputStream();
            InputStream fis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            //获取文件的名字再浏览器下载页面
            String name = file.getName();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "iso-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            out.write(buffer);
            out.flush();
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 用户邮箱注册
     * @return
     */
    @PostMapping("/register")
    public R<?> register(@RequestBody UserDTO userDTO){
        userService.registerUser(userDTO);
        return R.success("注册成功");
    }

    /**
     * 注册-发送邮箱验证码
     * @param emailUrl
     * @return
     */
    @GetMapping("/sendEmail")
    public R<?> sendEmail(String emailUrl){
        //type=1注册 ，type=2修改密码
        String mailId = RandomUtil.randomNumbers(6);
        String content = """
               您好！
                   本次验证码是：
               """;
        emailService.sendEmail(emailUrl,"校园拼课系统修改密码验证码", content + mailId);
        redisCache.setCacheObject(UPLOAD_PASSWORD + emailUrl,mailId,120, TimeUnit.SECONDS);
        return R.success("发送成功");
    }

    /**
     * 注册-发送邮箱验证码
     * @param emailUrl
     * @return
     */
    @GetMapping("/sendRegisEmail")
    public R<?> sendRegisEmail(String emailUrl){
        //type=1注册 ，type=2修改密码
        String mailId = RandomUtil.randomNumbers(6);
        String content = """
               您好！
                   本次验证码是：
               """;
        emailService.sendEmail(emailUrl,"校园拼课系统注册验证码", content + mailId);
        redisCache.setCacheObject(REGISTER_CODE + emailUrl,mailId,120, TimeUnit.SECONDS);
        return R.success("发送成功");
    }

    /**
     * 通过邮箱修改密码
     * @param userPasswordDto
     * @return
     */
    @PostMapping("/uploadPassword")
    public R<?> uploadPassword(@RequestBody UserPasswordDto userPasswordDto){
        userService.uploadPassword(userPasswordDto);
        return R.success("修改成功");
    }

    /**
     * 获取用户列表
     * @return
     */
    @GetMapping("/getUserList")
    public R<IPage<UserDTO>> getUserList(int pageNum, int pageSize, String username, String email){
        IPage<UserDTO> userDTO = userService.getUserPage(pageNum, pageSize, username, email);
        return R.success(userDTO);
    }

    @DeleteMapping("/delete")
    public R<?> deleteUser(Integer id){
        userService.deleteUser(id);
        return R.success("删除成功");
    }

    /**
     * 人员信息修改
     * @param userDTO
     * @return
     */
    @PostMapping("/update")
    public R<?> updateUser(@RequestBody UserDTO userDTO){
        userService.updateUser(userDTO);
        return R.success("修改成功");
    }

    /**
     * 通过用户主键id获取用户全部基本信息
     * @param id
     * @return
     */
    @GetMapping("/getUserDetail")
    public R<UserDTO> getUserDetail(Long id) {
        UserDTO userInfo = userService.getUserDetail(id);
        return R.success(userInfo);
    }
}
